const app = getApp()
const i18n = require('../../utils/i18n/index')

Page({
  data: {
    supplyList: [],
    categories: [],
    types: [
      { id: 0, name: '供应', name_en: 'Supply' },
      { id: 1, name: '需求', name_en: 'Demand' }
    ],
    categoryIndex: -1,
    typeIndex: -1,
    page: 1,
    hasMore: true,
    loading: false,
    refreshing: false,
    keyword: '',
    cdnUrl: '',
    locale: 'zh_CN',
    t: {},
    currentTab: 'all',
    list: []
  },
  onShow() {
    // 更新导航栏标题
    wx.setNavigationBarTitle({
        title: i18n.getLocale()=='en_US'?'Member':'成员名单'
    });
  },
  onLoad() {
    this.setData({
      cdnUrl: app.globalData.cdnUrl
    })
    this.setI18nData()
    this.loadCategories()
    this.loadSupplyList()

    // 监听语言变更事件
    const self = this
    app.globalData.eventBus.on('localeChanged', function() {
      self.setI18nData()
      self.loadSupplyList()
    })
  },

  onUnload() {
    // 移除事件监听
    app.globalData.eventBus.off('localeChanged')
  },

  setI18nData() {
    this.setData({
      locale: i18n.getLocale(),
      t: {
        title: i18n.t('supply.title'),
        tabAll: i18n.t('supply.tabs.all'),
        tabSupply: i18n.t('supply.tabs.supply'),
        tabDemand: i18n.t('supply.tabs.demand'),
        searchPlaceholder: i18n.t('common.search'),
        categoryPlaceholder: i18n.t('supply.categorymPlaceholder'),
        typePlaceholder: i18n.t('supply.typePlaceholder'),
        loading: i18n.t('common.loading'),
        noMore: i18n.t('supply.noMore'),
        empty: i18n.t('supply.empty'),
        publish: i18n.t('supply.publish.btn'),
        loginRequired: i18n.t('supply.loginRequired'),
      }
    })
  },

  onLanguageChange() {
    this.setI18nData()
  },

  // 加载分类数据
  loadCategories() {
    const self = this
    wx.request({
      url: app.globalData.baseUrl + 'public/member-categories',
      success: function(res) {
        if (res.data.code === 0) {
            const categories = res.data.data.categories
            categories.unshift({ id: '', name: '全部' });
          self.setData({
            categories:  categories|| []
          })
        }
      }
    })
  },

  // 加载供需列表
  loadSupplyList: function(isRefresh) {
    if (this.data.loading) return

    const self = this
    this.setData({ loading: true })
    const data = this.data
    
    wx.request({
      url: app.globalData.baseUrl + 'public/members',
      data: {
        page: data.page,
        category_id: data.categoryIndex >= 0 ? data.categories[data.categoryIndex].id : '',
        type: data.typeIndex >= 0 ? data.types[data.typeIndex].id : '',
        keyword: data.keyword,
        locale: data.locale
      },
      success: function(res) {
        if (res.data.code === 0) {
          const list = res.data.data.needs || []
          const newList = isRefresh ? list : data.supplyList.concat(list)
          self.setData({
            supplyList: newList,
            hasMore: list.length === 10,
            page: isRefresh ? 1 : data.page + 1
          })
        }
      },
      complete: function() {
        self.setData({
          loading: false,
          refreshing: false
        })
      }
    })
  },

  // 搜索处理
  onSearch: function(e) {
    const self = this
    this.setData({
      keyword: e.detail.value,
      page: 1,
      supplyList: []
    }, function() {
      self.loadSupplyList(true)
    })
  },

  // 分类选择处理
  onCategoryChange: function(e) {
    const self = this
    this.setData({
      categoryIndex: Number(e.detail.value),
      page: 1,
      supplyList: []
    }, function() {
      self.loadSupplyList(true)
    })
  },

  // 类型选择处理
  onTypeChange: function(e) {
    const self = this
    this.setData({
      typeIndex: Number(e.detail.value),
      page: 1,
      supplyList: []
    }, function() {
      self.loadSupplyList(true)
    })
  },

  // 加载更多
  onLoadMore: function() {
    if (this.data.hasMore && !this.data.loading) {
      this.loadSupplyList()
    }
  },

  // 下拉刷新
  onRefresh: function() {
    const self = this
    this.setData({
      refreshing: true,
      page: 1,
      supplyList: []
    }, function() {
      self.loadSupplyList(true)
    })
  },

  // 点击供需项
  onItemTap: function(e) {
    const id = e.currentTarget.dataset.id
    wx.navigateTo({
      url: '/pages/member/detail/detail?id=' + id
    })
  },

  // 点击发布
  onPublishTap: function() {
    const self = this
    if (!app.globalData.isLogin) {
      wx.showModal({
        title: i18n.t('common.confirm'),
        content: this.data.t.loginRequired,
        confirmText: i18n.t('mine.login'),
        success: function(res) {
          if (res.confirm) {
            wx.navigateTo({
              url: '/pages/mine/login/login'
            })
          }
        }
      })
      return
    }
    wx.navigateTo({
      url: '/pages/supply/publish/publish'
    })
  },

  // 切换标签
  switchTab: function(e) {
    const tab = e.currentTarget.dataset.tab
    this.setData({ currentTab: tab })
    this.loadList(tab)
  },

  // 加载列表数据
  loadList: function(tab) {
    const self = this
    if (!tab) tab = 'all'
    
    wx.request({
      url: app.globalData.baseUrl + 'supply/list',
      data: {
        type: tab
      },
      success: function(res) {
        if (res.data.code === 0) {
          self.setData({
            list: res.data.data || []
          })
        }
      }
    })
  },

  // 分享按钮点击
  onShareTap() {
    wx.showShareMenu({
      withShareTicket: true,
      menus: ['shareAppMessage', 'shareTimeline']
    })
  },

  // 分享
  onShareAppMessage() {
    return {
      title: i18n.getLocale()=='en_US'?'Member':'成员名单',
      path: `pages/member/member`
    }
  },
  onShareTimeline() {
    return {
      title: i18n.getLocale()=='en_US'?'Member':'成员名单',
      path: `pages/member/member`
    }
  }
}) 